﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace SVNHelper
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void FindSvnButton_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog { Filter = "Svn.exe|Svn.exe" };
            openFileDialog.InitialDirectory = Directory.GetCurrentDirectory();
            var result = openFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                SvnPathTextBox.Text = openFileDialog.FileName;
                Properties.Settings.Default["SvnPath"] = openFileDialog.FileName;
                Properties.Settings.Default.Save();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\svn.exe"))
            {
                SvnPathTextBox.Text = Application.StartupPath + "\\svn.exe";
            }
            else
            {
                SvnPathTextBox.Text = Properties.Settings.Default.SvnPath;
            }
            PathTextBox.Text = Properties.Settings.Default.DefaultWorkingPath;
        }

        private void ExportButton_Click(object sender, EventArgs e)
        {
            var processStartInfo = new ProcessStartInfo(SvnPathTextBox.Text);
            processStartInfo.UseShellExecute = false;
            processStartInfo.CreateNoWindow = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.RedirectStandardOutput = true;
            if (!string.IsNullOrEmpty(UTextBox.Text))
            {
                processStartInfo.Arguments = string.Format("log -r {{{0}}}:{{{1}}} --username {3} --password {4} {2}",
                                            StartDateTimePicker.Value.ToShortDateString(),
                                            EndDateTimePicker.Value.ToShortDateString(), PathTextBox.Text, UTextBox.Text, PTextBox.Text);
            }
            else
            {
                processStartInfo.Arguments = string.Format("log -r {{{0}}}:{{{1}}} {2}",
                                                           StartDateTimePicker.Value.ToShortDateString(),
                                                           EndDateTimePicker.Value.ToShortDateString(), PathTextBox.Text);
            }

            var process = Process.Start(processStartInfo);
            var logContent = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            ExportToExcel(logContent);
        }

        private void ExportToExcel(string logContent)
        {
            var stringReader = new StringReader(logContent);
            string logLine;
            string[] detailInfo;
            string logLineCountString;
            int unknownIssue = 0;
            DataTable dataTable = CreateLogTable();
            var issueRegex = new Regex(string.Format("{0}\\s*-\\s*\\d+", PrefixTextBox.Text), RegexOptions.IgnoreCase);

            do
            {
                var logMessage = string.Empty;
                stringReader.ReadLine();
                logLine = stringReader.ReadLine();
                if (logLine == null) break;
                detailInfo = logLine.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                logLineCountString = detailInfo[detailInfo.Length - 1].Trim();
                var logLineCount = int.Parse(logLineCountString.Substring(0, logLineCountString.IndexOf(' ')));
                stringReader.ReadLine();
                for (var i = 0; i < logLineCount; i++)
                {
                    logMessage += stringReader.ReadLine();
                }
                if (UserTextBox.Text.Equals(detailInfo[1].Trim(), StringComparison.CurrentCultureIgnoreCase))
                {
                    var match = issueRegex.Match(logMessage);
                    string issueNumber = match.Success ? match.Value : string.Format("N/A{0}", unknownIssue++);

                    var dataRow = dataTable.NewRow();
                    dataRow[0] = detailInfo[2].Substring(0, 11);
                    dataRow[1] = issueNumber;
                    dataRow[2] = logMessage;
                    dataRow[3] = detailInfo[1];
                    try
                    {
                        dataTable.Rows.Add(dataRow);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            } while (true);

            if (!Directory.Exists(Application.StartupPath + "\\Exported")) Directory.CreateDirectory(Application.StartupPath + "\\Exported");
            string fileName = string.Format(Application.StartupPath + "\\Exported\\{0}-{1}.csv",
                                            UserTextBox.Text,
                                            "Timesheet");
            var streamWriter = new StreamWriter(fileName);
            foreach (DataRow row in dataTable.Rows)
            {
                streamWriter.WriteLine(string.Format("{0},{1},{2},{3}", DateTime.Parse(row[0].ToString()).ToString("yyyyMMdd"), row[1], row[2], row[3]));
            }
            streamWriter.Flush();
            streamWriter.Close();
            MessageBox.Show(this, "导出完成.");
        }

        private static DataTable CreateLogTable()
        {
            var dataTable = new DataTable();
            dataTable.Columns.Add("Date", typeof(string));
            dataTable.Columns.Add("Issue", typeof(string));
            dataTable.Columns.Add("Log", typeof(string));
            dataTable.Columns.Add("Author", typeof(string));
            dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns[0], dataTable.Columns[1] };
            dataTable.AcceptChanges();
            return dataTable;
        }

        private void AboutButton_Click(object sender, EventArgs e)
        {
            FormAbout formAbout = new FormAbout();
            formAbout.Show();
        }
    }
}
